<template>
  <div class="container mx-auto px-4 py-6">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-semibold text-gray-800">实验室管理</h2>
      <button @click="showCreateDialog = true" class="flex items-center px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
        <PlusIcon class="h-5 w-5 mr-2" />
        添加实验室
      </button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
      <form @submit.prevent="handleSearch" class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
          <label for="name" class="block text-sm font-medium text-gray-700">实验室名称</label>
          <input type="text" id="name" v-model="searchForm.name" placeholder="请输入实验室名称" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
        </div>
        <div>
          <label for="location" class="block text-sm font-medium text-gray-700">位置</label>
          <input type="text" id="location" v-model="searchForm.location" placeholder="请输入位置" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
        </div>
        <div>
          <label for="managerName" class="block text-sm font-medium text-gray-700">负责人</label>
          <input type="text" id="managerName" v-model="searchForm.managerName" placeholder="请输入负责人姓名" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
        </div>
        <div>
          <label for="status" class="block text-sm font-medium text-gray-700">状态</label>
          <select id="status" v-model="searchForm.status" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <option value="">全部状态</option>
            <option value="1">启用</option>
            <option value="0">禁用</option>
          </select>
        </div>
        <div class="md:col-span-4 flex justify-end space-x-3 mt-4">
          <button type="submit" class="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">搜索</button>
          <button type="button" @click="handleReset" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">重置</button>
        </div>
      </form>
    </div>

    <!-- 实验室列表 -->
    <div class="bg-white rounded-xl shadow-lg p-6">
      <div v-if="loading" class="text-center py-8">
        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div>
        <p class="mt-2 text-gray-500">加载中...</p>
      </div>
      <div v-else class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">实验室名称</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">位置</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">负责人</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">联系电话</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="laboratory in laboratories" :key="laboratory.id">
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ laboratory.name }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ laboratory.location }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ laboratory.managerName }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ laboratory.managerPhone }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm">
                <span :class="['px-2 inline-flex text-xs leading-5 font-semibold rounded-full', laboratory.status === 1 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800']">
                  {{ laboratory.statusText }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ formatDate(laboratory.createTime) }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button @click="editLaboratory(laboratory)" class="text-indigo-600 hover:text-indigo-900 mr-3">编辑</button>
                <button @click="deleteLaboratory(laboratory)" class="text-red-600 hover:text-red-900">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="flex justify-end mt-6">
        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
          <button @click="handleCurrentChange(pagination.current - 1)" :disabled="pagination.current === 1" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
            <span class="sr-only">Previous</span>
            <ChevronLeftIcon class="h-5 w-5" aria-hidden="true" />
          </button>
          <button v-for="page in totalPages" :key="page" @click="handleCurrentChange(page)" :class="['relative inline-flex items-center px-4 py-2 border text-sm font-medium', page === pagination.current ? 'z-10 bg-indigo-50 border-indigo-500 text-indigo-600' : 'bg-white border-gray-300 text-gray-700 hover:bg-gray-50']">
            {{ page }}
          </button>
          <button @click="handleCurrentChange(pagination.current + 1)" :disabled="pagination.current === totalPages" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
            <span class="sr-only">Next</span>
            <ChevronRightIcon class="h-5 w-5" aria-hidden="true" />
          </button>
        </nav>
        <div class="ml-4 flex items-center text-sm text-gray-700">
          <span>共 {{ pagination.total }} 条</span>
          <select v-model="pagination.size" @change="handleSizeChange($event.target.value)" class="ml-2 block w-auto pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md">
            <option :value="10">10 条/页</option>
            <option :value="20">20 条/页</option>
            <option :value="50">50 条/页</option>
            <option :value="100">100 条/页</option>
          </select>
        </div>
      </div>
    </div>

    <!-- 创建/编辑实验室对话框 -->
    <div v-if="showCreateDialog || showEditDialog" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
      <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <div class="mt-3">
          <h3 class="text-lg font-medium text-gray-900 mb-4">
            {{ showCreateDialog ? '添加实验室' : '编辑实验室' }}
          </h3>
          <form @submit.prevent="handleSubmit">
            <div class="space-y-4">
              <div>
                <label for="formName" class="block text-sm font-medium text-gray-700">实验室名称</label>
                <input type="text" id="formName" v-model="form.name" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
              </div>
              <div>
                <label for="formLocation" class="block text-sm font-medium text-gray-700">位置</label>
                <input type="text" id="formLocation" v-model="form.location" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
              </div>
              <div>
                <label for="formDescription" class="block text-sm font-medium text-gray-700">描述</label>
                <textarea id="formDescription" v-model="form.description" rows="3" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"></textarea>
              </div>
              <div>
                <label for="formManagerName" class="block text-sm font-medium text-gray-700">负责人姓名</label>
                <input type="text" id="formManagerName" v-model="form.managerName" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
              </div>
              <div>
                <label for="formManagerPhone" class="block text-sm font-medium text-gray-700">联系电话</label>
                <input type="tel" id="formManagerPhone" v-model="form.managerPhone" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
              </div>
              <div>
                <label for="formStatus" class="block text-sm font-medium text-gray-700">状态</label>
                <select id="formStatus" v-model="form.status" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                  <option value="1">启用</option>
                  <option value="0">禁用</option>
                </select>
              </div>
            </div>
            <div class="flex justify-end space-x-3 mt-6">
              <button type="button" @click="closeDialog" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">取消</button>
              <button type="submit" :disabled="submitting" class="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 disabled:opacity-50">
                {{ submitting ? '保存中...' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import request from '@/utils/request'
import {
  PlusIcon,
  ChevronLeftIcon,
  ChevronRightIcon
} from '@heroicons/vue/24/outline'

const laboratories = ref([])
const loading = ref(false)
const submitting = ref(false)
const showCreateDialog = ref(false)
const showEditDialog = ref(false)

const searchForm = reactive({
  name: '',
  location: '',
  managerName: '',
  status: ''
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const form = reactive({
  id: null,
  name: '',
  location: '',
  description: '',
  managerName: '',
  managerPhone: '',
  status: 1
})

const totalPages = computed(() => Math.ceil(pagination.total / pagination.size))

// 加载实验室列表
const loadLaboratories = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }

    const response = await request.get('/laboratories/list', { params })
    laboratories.value = response.data.records
    pagination.total = response.data.total

  } catch (error) {
    console.error('加载实验室列表失败:', error)
    showMessage('加载实验室列表失败', 'error')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadLaboratories()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    location: '',
    managerName: '',
    status: ''
  })
  pagination.current = 1
  loadLaboratories()
}

// 页面大小改变
const handleSizeChange = (size) => {
  pagination.size = parseInt(size)
  pagination.current = 1
  loadLaboratories()
}

// 当前页改变
const handleCurrentChange = (current) => {
  if (current < 1 || current > totalPages.value) return
  pagination.current = current
  loadLaboratories()
}

// 编辑实验室
const editLaboratory = (laboratory) => {
  Object.assign(form, {
    id: laboratory.id,
    name: laboratory.name,
    location: laboratory.location,
    description: laboratory.description || '',
    managerName: laboratory.managerName,
    managerPhone: laboratory.managerPhone,
    status: laboratory.status
  })
  showEditDialog.value = true
}

// 删除实验室
const deleteLaboratory = async (laboratory) => {
  if (!confirm(`确定要删除实验室"${laboratory.name}"吗？`)) return

  try {
    await request.delete(`/laboratories/${laboratory.id}`)
    showMessage('删除成功', 'success')
    loadLaboratories()
  } catch (error) {
    console.error('删除实验室失败:', error)
    showMessage('删除实验室失败', 'error')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    submitting.value = true

    if (showCreateDialog.value) {
      await request.post('/laboratories', form)
      showMessage('创建成功', 'success')
    } else {
      await request.put('/laboratories', form)
      showMessage('更新成功', 'success')
    }

    closeDialog()
    loadLaboratories()
  } catch (error) {
    console.error('保存实验室失败:', error)
    showMessage('保存实验室失败', 'error')
  } finally {
    submitting.value = false
  }
}

// 关闭对话框
const closeDialog = () => {
  showCreateDialog.value = false
  showEditDialog.value = false
  Object.assign(form, {
    id: null,
    name: '',
    location: '',
    description: '',
    managerName: '',
    managerPhone: '',
    status: 1
  })
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 简单消息显示函数
const showMessage = (message, type = 'info') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'success' ? 'bg-green-500' :
    type === 'warning' ? 'bg-yellow-500' :
    type === 'error' ? 'bg-red-500' :
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)

  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}

onMounted(() => {
  loadLaboratories()
})
</script>